//
//  CMDBHomeTrendTopicCell.swift
//  CMDB
//
//  Created by 曹桂祥 on 17/4/10.
//  Copyright © 2017年 CMDB. All rights reserved.
//

import UIKit

private let KCollectionID = "KCollectionID"

private let picViewWH : CGFloat = (CMDB_Screen_Width - 2 * KleftMargin - 5 * 2) / 3

private let rowCount : Int          = 3

private let picMargin : CGFloat     = 5

private let maxTotalWidth : Int = 270

class CMDBHomeTrendTopicCell: CustomBaseCell {
    
    var tags : [CMDBAtibuteTagBean] = [CMDBAtibuteTagBean]()
    
    lazy var tagsCollectionView : CMDBTagsCollectionView = {
        
        let collectionView = CMDBTagsCollectionView.getInstance()

        return collectionView
        
    }()
    
    var iconImageView : UIImageView = UIImageView.getInstance()
    
    var nameLabel : UILabel         = UILabel.getInstance()
    
    var timeLabel : UILabel         = UILabel.getInstance()
    
    var contentLabel : UILabel      = UILabel.getInstance()
  
    var toolView : UIView           = UIView.getInstance()
    
    var likeButton : UIButton       = UIButton.getInstance()
    
    var collectButton : UIButton    = UIButton.getInstance()
    
    var forwardButton : UIButton    = UIButton.getInstance()
    
    var commentButton : UIButton    = UIButton.getInstance()
    
    var separateView  : UIView      = UIView.getInstance()
    
    var picsView      : UIView      = UIView.getInstance()
    
    var contentSize : CGSize?
    
    let btnWidth : CGFloat          = CMDB_Screen_Width / 4
    
    var pictureViewH : CGFloat      = 0
    
    var urls : [CMDBPictureMdeol]   = [CMDBPictureMdeol]()
    
    var topicData : CMDBDynamicBean!
    
    override func setupCell() {
        super.setupCell()
        
        backgroundColor = UIColor.whiteColor()
    }
    
    override func cellBuildSubViews() {
        super.cellBuildSubViews()
        
        iconImageView.frame               = CGRect(x: KleftMargin, y: KleftMargin, width: 40, height: 40)
        
        iconImageView.layer.cornerRadius  = 5
        
        iconImageView.layer.masksToBounds = true
        
        contentView.addSubview(iconImageView)
        
        nameLabel.frame                   = CGRect(x: CGRectGetMaxX(self.iconImageView.frame) + KleftMargin, y: KleftMargin, width: 100, height: 16)
        nameLabel.font                    = CMDB_16_Bold_FONT
        
        contentView.addSubview(nameLabel)
        
        timeLabel.font                    = CMDB_12_FONT
        timeLabel.textColor               = word38Color
        timeLabel.sizeToFit()

        contentView.addSubview(timeLabel)
        
        contentLabel.numberOfLines        = 0
        
        contentLabel.font                 = CMDB_16_FONT
        
        contentLabel.textColor            = word87Color
        
        contentView.addSubview(contentLabel)
        
        likeButton       = UIButton(title: "赞", imageName: "赞", selectedImage: "赞-选中", isSizeToFit: false,color: word54Color,titleSizeFont: CMDB_12_FONT)
        
        likeButton.frame = CGRect(x: 0, y: 0, width: btnWidth, height: 36)
        
        likeButton.addTarget(self, action: #selector(likeClicked), forControlEvents: .TouchUpInside)
        
        toolView.addSubview(likeButton)
        
        collectButton       = UIButton(title: "收藏", imageName: "收藏", selectedImage: "收藏-选中", isSizeToFit: false,color: word54Color,titleSizeFont: CMDB_12_FONT)
        collectButton.frame = CGRect(x: btnWidth, y: 0, width: btnWidth, height: 36)
        
        toolView.addSubview(collectButton)
        
        forwardButton       = UIButton(title: "转发", imageName: "转发", selectedImage: "转发-选中", isSizeToFit: false,color: word54Color,titleSizeFont: CMDB_12_FONT)
        forwardButton.frame = CGRect(x: btnWidth * 2, y: 0, width: btnWidth, height: 36)
    
        toolView.addSubview(forwardButton)
        
        commentButton       = UIButton(title: "评论", imageName: "评论", selectedImage: "评论-选中", isSizeToFit: false,color: word54Color,titleSizeFont: CMDB_12_FONT)
        commentButton.frame = CGRect(x: btnWidth * 3, y: 0, width: btnWidth, height: 36)
        
        toolView.addSubview(commentButton)
        
        let topLine         = UIView(frame:CGRect(x: 0, y: 0, width: CMDB_Screen_Width, height: 0.5))
        
        topLine.backgroundColor = UIColor.Hex6(0x000000, alpha: 0.12)
        
        toolView.addSubview(topLine)
        
        let bottomLine      = UIView(frame:CGRect(x:0, y: 35.5, width: CMDB_Screen_Width, height: 0.5))
        
        bottomLine.backgroundColor = UIColor.Hex6(0x000000, alpha: 0.12)
        
        toolView.addSubview(bottomLine)

        
        contentView.addSubview(toolView)
        
        separateView.backgroundColor = UIColor.Hex6(0xf2f2f2)
        
        contentView.addSubview(separateView)
    }
    
    override func loadContent() {
        topicData       = cellData as! CMDBDynamicBean
        
        if (Int(topicData.commentCount)) > 0 {
            commentButton.setTitle(topicData.commentCount, forState: .Normal)
        }else{
            commentButton.setTitle("评论", forState: .Normal)
        }

        if (Int(topicData.isCollect) == 1) {
            collectButton.selected = true
        }else{
            collectButton.selected = false
        }
        
        if (Int(topicData.likeCount) > 0) {
            
            if (Int(topicData.isLike) == 1) {
                likeButton.selected = true
                
                likeButton.setTitle(topicData.likeCount, forState: .Selected)
            }else{
                likeButton.setTitle(topicData.likeCount, forState: .Normal)
                likeButton.setImage(UIImage(named: "赞"), forState: .Normal)
            }
            
        }else{
            likeButton.selected = false
            likeButton.setTitle("赞", forState: .Normal)
        }
        
        iconImageView.setHeader(topicData.user?.icon)
        
        nameLabel.text      = topicData.user?.name
        
        timeLabel.text      = topicData.createTimeFormat
        
        timeLabel.sizeToFit()
        
        timeLabel.frame = CGRect(x: CMDB_Screen_Width - KleftMargin - timeLabel.width, y: 20, width: timeLabel.width, height: timeLabel.height)
        
        contentLabel.text   = topicData.content
        
        contentSize         = topicData.content.suitToSize(CGSize(width: CMDB_Screen_Width - 2 * KleftMargin,height: 999), fontSize: 16, lineSpacing: 2)
        
        contentLabel.frame  = CGRect(x: KleftMargin, y: CGRectGetMaxY(self.iconImageView.frame) + 0.5 * KleftMargin, width: CMDB_Screen_Width - 2 * KleftMargin, height: contentSize!.height)
        
        
        if !topicData.imgs.isEmpty {
            
            picsView.removeFromSuperview()
            
            setupPictureView(topicData.imgs)
            
        }else {
            
            picsView.hidden = true
            
            pictureViewH = 0
            
        }
        
        separateView.snp_makeConstraints { (make) in
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.bottom.equalTo(0)
            make.height.equalTo(10)
        }
        
        toolView.snp_makeConstraints { (make) in
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.bottom.equalTo(-10)
            make.height.equalTo(36)
        }
        
        if topicData.cellHeight == 0 {

            layoutIfNeeded()
            
            topicData.cellHeight = CGRectGetMaxY(contentLabel.frame) + toolView.height + separateView.height + 5 + pictureViewH + 10
        }
        
        if topicData.user?.atags?.count > 0 {
            contentView.addSubview(tagsCollectionView)
            
            tagsCollectionView.frame = CGRect(x: CGRectGetMinX(nameLabel.frame), y: CGRectGetMaxY(nameLabel.frame) + 6, width: 200, height: 20)
            
            tagsCollectionView.tags = topicData.user!.atags!
        }
    }
}

//MARK: 设置cell里面的子控件
extension CMDBHomeTrendTopicCell {
    
    func setupPictureView(imagesUrls : String){
        
        var picWidth : CGFloat = 0
        
        let picsView         = UIView.getInstance()
        
        self.picsView        = picsView
        
        self.picsView.hidden = false
        
        let imageUrlData = imagesUrls.dataUsingEncoding(NSUTF8StringEncoding)
        
        do {
            
            let urlArray = try NSJSONSerialization.JSONObjectWithData(imageUrlData!, options: .AllowFragments) as! [[String : AnyObject]]
            
            urls         = CMDBPictureMdeol.objectArrayWithKeyValuesArray(urlArray as NSArray) as! [CMDBPictureMdeol]
            
            let picModel = urls.first
            
            for (index,pictureModel) in urls.enumerate() {
                
                let row               = index / rowCount
                
                let col               = index % rowCount
                
                let picView           = UIImageView.getInstance()
                
                picView.userInteractionEnabled = true
                
                picView.contentMode   = .ScaleToFill
                
                picView.clipsToBounds = true

                picView.frame         = CGRect(x: KleftMargin + CGFloat(col) * (picViewWH + 5), y: CGFloat(row) * (picViewWH + picMargin), width: picViewWH, height: picViewWH)
                
                if urls.count == 1 {
                    if String.stringToInt(urls.first!.width) > maxTotalWidth && String.stringToInt(urls.first!.height) < maxTotalWidth{
                        
                        pictureViewH = CGFloat(maxTotalWidth) / CGFloat(1.3)
                        
                        picWidth     = CGFloat(maxTotalWidth)
                        
                    }else if String.stringToInt(urls.first!.height) > maxTotalWidth && String.stringToInt(urls.first!.width) < maxTotalWidth{
                        
                        pictureViewH = CGFloat(maxTotalWidth)
                        
                        picWidth     = CGFloat(maxTotalWidth) / CGFloat(1.3)
                        
                    }else if String.stringToInt(urls.first!.height) > maxTotalWidth && String.stringToInt(urls.first!.width) > maxTotalWidth{
                        
                        if String.stringToInt(urls.first!.width)  / String.stringToInt(urls.first!.height) > 1 {
                            pictureViewH = CGFloat(maxTotalWidth) / CGFloat(1.3)
                            
                            picWidth     = CGFloat(maxTotalWidth)

                        }else{
                            
                            pictureViewH = CGFloat(maxTotalWidth)
                            
                            picWidth     = CGFloat(maxTotalWidth) / CGFloat(1.3)
                        }
                    
                    }else{
                        
                        let nf = NSNumberFormatter()
                        
                        nf.numberStyle = .DecimalStyle
                        
                        let height = nf.numberFromString(pictureModel.height) ?? 0
                        
                        pictureViewH = CGFloat(height.floatValue)
                        
                        let width = nf.numberFromString(pictureModel.width) ?? 0
                        
                        picWidth     = CGFloat(width.floatValue)

                    }
                    
                    picView.frame         = CGRect(x: KleftMargin, y: picMargin, width: picWidth, height: pictureViewH)
                }
                
                picView.loadPicImage(pictureModel.url)
                
                picView.tag           = index
                
                self.tapGestureOnImageView(picView)
                
                picsView.addSubview(picView)
                
            }
           
            if urls.count == 1 {
                
                if String.stringToInt(urls.first!.width) > maxTotalWidth && String.stringToInt(urls.first!.height) < maxTotalWidth{
                    
                    pictureViewH = CGFloat(maxTotalWidth) / CGFloat(1.3)
                    
                    picWidth     = CGFloat(maxTotalWidth)
                }else if String.stringToInt(urls.first!.height) > maxTotalWidth && String.stringToInt(urls.first!.width) < maxTotalWidth{
                    
                    pictureViewH = CGFloat(maxTotalWidth)
                    
                    picWidth     = CGFloat(maxTotalWidth) / CGFloat(1.3)
                }else if String.stringToInt(urls.first!.height) > maxTotalWidth && String.stringToInt(urls.first!.width) > maxTotalWidth{
                    
                    if String.stringToInt(urls.first!.width)  / String.stringToInt(urls.first!.height) > 1 {
                        pictureViewH = CGFloat(maxTotalWidth) / CGFloat(1.3)
                        
                        picWidth     = CGFloat(maxTotalWidth)
                        
                    }else{
                        
                        pictureViewH = CGFloat(maxTotalWidth)
                        
                        picWidth     = CGFloat(maxTotalWidth) / CGFloat(1.3)
                    }
                    
                }else{
                    
                    pictureViewH = CGFloat(String.stringToInt((picModel?.height)!))
                    
                    picWidth     = CGFloat(String.stringToInt(picModel!.width))
                    
                }
                
            }else if  urls.count > 3 && urls.count < 7{
                
                pictureViewH = picViewWH * 2 + picMargin
                
                
            }else if urls.count > 1 && urls.count < 4{
            
                pictureViewH = picViewWH
                
            }else{
                
                pictureViewH = picViewWH * 3 + picMargin * 2
                
            }
            
            picsView.frame = CGRect(x: 0, y: CGRectGetMaxY(contentLabel.frame) + 5, width: CMDB_Screen_Width, height: pictureViewH + 10)
            
            contentView.addSubview(picsView)
            
        }catch _ as NSError{
            
            printLog("fail")
            
        }
        
    }
    
}


//MARK: 图片添加手势
extension CMDBHomeTrendTopicCell{
    
    func tapGestureOnImageView(imageView: UIImageView) {
        //建立手势识别器
        let gesture = UITapGestureRecognizer(target: self, action: #selector(tapOnView(_:)))
        //附加识别器到视图
        imageView.addGestureRecognizer(gesture)
    }
    
}

//MARK:  action methods
extension CMDBHomeTrendTopicCell{
    
    @objc func tapOnView(tapGes: UITapGestureRecognizer){
        
        mDelegate?.onItemClickType!("TapOnView", data: urls, indexPath: NSIndexPath(index: tapGes.view!.tag))
    }
    
    
    @objc func likeClicked(){
        
        if topicData.isLike == "1" {
            
        }else{
            
            let likeCount =  String.stringToInt(topicData.likeCount)
            
            likeButton.setTitle("\(likeCount + 1)", forState: .Normal)
            
            likeButton.selected = true
            
            likeButton.setImage(UIImage(named:"赞-选中"), forState: .Selected)
            
            mDelegate?.onItemClickType!(("HomeTopicLike"), data: (cellData as! CMDBDynamicBean).tid, indexPath: nil)
            
        }
    }
}

